<template>
  <div class="Chat">
    <!-- <div class="chatToper">
      <div class="toperName">{{ toperMessage }}</div>
    </div> -->
    <div class="chatPage">
      <Chat ref="chat" :history-message="data.historyMessage" :self="self" :jargon="data.jargon"
        :user-type="data.userType" @submit-remark="value => {
          setUserRemark({
            conversation_id: self['id'],
            remarks: value,
          });
        }
          " @change-follow-up-date="value => {
            upFollowUpDate({
              conversation_id: self['id'],
              follow_time: value,
            });
          }
            " @change-user-type="item => {
              setUserType({
                conversation_id: self['id'],
                type: item['value'],
              });
            }
              " @enter="event.sendMessage" />
      <!-- 这里是接收到子组件传递的事件名@enter 并调用event中的sendMessage这个方法 将子组件传过来的数据带入进去  -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { getUserList, getMessage, setUserRemark, upFollowUpDate, sendMessage, setUserType, getJargon } from '@/api';
import { nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import type { IData } from '@/components/user-list/interface';
import Chat from '@/components/chat/Chat.vue';

const chat = ref<InstanceType<typeof Chat> | null>()
const userList = ref()
const toperMessage = ref('会话')
// 获取到储存在浏览器的数据
// JSON.parse不接受空值
const selfId = JSON.parse(localStorage.getItem('selfId') || '')
const selfJson = ref<string>(localStorage.getItem('self') || '')
const self: Record<string, any>[] | any = selfJson.value ? JSON.parse(selfJson.value) : []
// function scrollToBottom() {
//   // 调用子组件中暴露的孙组件的scrollToBottom方法
//   if (chat.value) {
//     console.log('chat有值,并且调用了滚动条到底的方法');
//     chat.value.scrollToBottom()
//   } else {
//     console.log('chat的值为空');
//   }
// }

const props = defineProps({
  type: {
    type: String,
    default: ''
  },
  followTime: {
    type: String,
    default: ''
  }
})

const data: IData = reactive({
  /**
   * 自己
   */
  self: {},
  /**
   * 搜索
   */
  search: '',
  /**
   * 用户列表
   */
  userList: [],
  /**
   * 历史信息
   */
  historyMessage: [],
  /**
   * 话术
   */
  jargon: {},
  /**
   * 用户评论
   */
  userComment: [],
  /**
   * 默认任务栏
   */
  defaultTabbar: 0,
  userType: [
    { name: '潜在客户', value: 0 },
    { name: '意向客户', value: 1 },
    { name: '成交客户', value: 2 },
    { name: '黑名单', value: 3 }
  ]
})


// 意为在所有DOM更新完之后的操作
// onMounted(() => {
//   nextTick(() => {
//     if (chat.value) {
//       console.log('chat有值');
//       chat.value.scrollToBottom()
//     } else {
//       console.log('chatP没有值');
//     }
//   })
// })


// 创建一个变量
const event = {
  // 获取用户列表
  async getUserList() {
    data.userList = await getUserList({
      keyword: data.search,
      type: props.type,
      follow_time: props.followTime
    })
  },

  // 获取历史聊天记录
  async getHistoryMessage() {
    data.historyMessage = await getMessage({
      conversation_id: selfId,
    });
  },

  /**
   * 获取话术
   */
  async getJargon() {
    const jargon = await getJargon()
    // 创建得data.jargon为一个空对象
    data.jargon = {};
    jargon.forEach(item => {
      const key = item['name'] as string
      const contents = item['info'].map((ite: Record<string, string>) => ite['content'])
      data.jargon[key] = contents
    })
  },

  /**
     * 
     * @param message 发送消息
     */
  async sendMessage(message: string) {

    console.log(message);

    nextTick(async () => {
      const status = await sendMessage({
        conversation_id: selfId,
        content: message,
      });
      if (chat.value && status) {
        // 这里异步等待获取到历史消息的方法 在让chat这个标识容器调用滚动条置底的方法
        // 因为发送了新的消息 在异步等待获取历史消息记录 然后就在调用滚动条到底的方法
        await event.getHistoryMessage()
        chat.value.scrollToBottom()
      }
    })
  },
}

watch(
  () => [props.type, props.followTime],
  () => {
    data.self = {};
    data.userComment = [];
    data.historyMessage = [];

    if (userList.value) {
      userList.value.reset();
    }
    clearInterval(data.historyMessagePollTimer);
    event.getUserList();
  },
);

onMounted(async () => {
  event.getUserList();
  data.userListPollTimer = setInterval(async () => {
    await event.getUserList();
  }, 1000);

  if (selfId) {
    await event.getHistoryMessage()
    // 获取到消息之后滚动条触底
    chat.value?.scrollToBottom();

    data.historyMessagePollTimer = setInterval(async () => {
      await event.getHistoryMessage()
    }, 3000)
  }
});

onUnmounted(() => {
  clearInterval(data.userListPollTimer);
  clearInterval(data.historyMessagePollTimer);
});
</script>

<style>
.Chat {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}

.toperName {
  font-size: 15px;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.chatToper {
  height: 5%;
  width: 100%;
  background-color: #ededed;
}

.chatPage {
  width: 100vw;
  height: 100%;
  position: relative;
  background-color: #f3f3f3;
  box-sizing: border-box;
  overflow-y: hidden;
}
</style>